package com.xhh.nphm;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.text.SimpleDateFormat;
import java.util.*;

public class AuthUtil {
    /**
     * 签名过期的时间，单位是秒
     */
    public static final Integer GUEST_SIGNATURE_EXPIRE_TIME = 300;

    /**
     * 认证标识字段名
     */
    public static final String AUTH_HEADER_KEY = "authorization";

    /**
     * 日期标识字段名
     */
    public static final String DATE_HEADER_KEY = "date";
    public static final String X_DATE_HEADER_KEY = "x-date";

    /**
     * 设置签名中的日期格式
     */
    private static final String DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss 'GMT'";

    /**
     * 设置时间区域
     */
    private static final String TIME_ZONE = "GMT";

    /**
     * 设置加密算法
     */
    private static final String ALGORITHM = "hmac-sha256";

    /**
     * 签名中的几个字段名
     */
    private static final String HEADER_START_FIELD = "hmac";
    private static final String HEADER_AK_FIELD = "username";
    private static final String HEADER_ALGORITHM_FIELD = "algorithm";
    private static final String HEADER_HEADER_FIELD = "headers";
    private static final String HEADER_SIGNATURE_FIELD = "signature";
    private static final String HEADER_DIGEST_FIELD = "digest";

    /**
     * 生成map的header
     *
     * @param headers
     * @param secretKey
     * @return
     */
    public static Map<String, String> builderHeader(Map<String, String> headers, String ak, String secretKey) {
        String akDecode = ak;
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT, Locale.ENGLISH);
        sdf.setTimeZone(TimeZone.getTimeZone(TIME_ZONE));
        String gmtTime = sdf.format(new Date());
        String signString = DATE_HEADER_KEY + ": " + gmtTime;
        String signature = sha256HMAC(signString, secretKey);
        StringBuilder authorization = new StringBuilder();
        authorization.append(HEADER_START_FIELD + " ");
        authorization.append(HEADER_AK_FIELD + "=" + akDecode + ", ");
        authorization.append(HEADER_ALGORITHM_FIELD + "=" + ALGORITHM + ", ");
        authorization.append(HEADER_HEADER_FIELD + "=" + DATE_HEADER_KEY + ", ");
        authorization.append(HEADER_SIGNATURE_FIELD + "=" + signature);
        headers.put(DATE_HEADER_KEY, gmtTime);
        headers.put(AUTH_HEADER_KEY, authorization.toString());
        return headers;
    }

    /**
     * 生成hmac sha256串
     *
     * @param message
     * @param secret
     * @return
     */
    public static String sha256HMAC(String message, String secret) {
        String result = null;
        try {
            Mac sha256HMAC = Mac.getInstance("HmacSHA256");
            SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
            sha256HMAC.init(secretKey);
            byte[] bytes = sha256HMAC.doFinal(message.getBytes());
            result = Base64.encodeBase64String(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 解析hmac header的鉴权串
     *
     * @param text
     * @return
     */
    private static Map<String, String> parseHmacString(String text) {
        Map<String, String> hmacMap = new HashMap<>();
        String[] textSplits = text.split(",");
        for (String textSplit : textSplits) {
            String[] rows = textSplit.split("=", 2);
            if (rows.length != 2) {
                continue;
            }
            String key = rows[0].trim();
            String value = trim(rows[1], '"').trim();
            hmacMap.put(key, value);
        }
        return hmacMap;
    }

    /**
     * 去掉指定字符串前面和后面指定的字符
     *
     * @param str
     * @param c
     * @return
     */
    private static String trim(String str, char c) {
        char[] chars = str.toCharArray();
        int len = chars.length;
        int st = 0;
        while ((st < len) && (chars[st] == c)) {
            st++;
        }
        while ((st < len) && (chars[len - 1] == c)) {
            len--;
        }
        return (st > 0) && (len < chars.length) ? str.substring(st, len) : str;
    }

    public static void main(String[] args) {
        String ak = "a9192d158c8146c39b1e55a4a1ae59fa";
        String sk = "gQgSaxZbZAFhgZfxU1Qrxh5Oi8Iy6OJy";
        Map<String, String> headers = new HashMap<>();
        Map<String, String> paramMap = builderHeader(headers, ak, sk);
        paramMap.put("Content-Type", "application/json");
        paramMap.put("x-bce-request-id", "1");
        String url = "http://scudmo.baidu.com/openapi/v1/event/analysis/part1/dugis/search?address=宽窄巷子&city=成都市";
        String result = "";
        String body = "";
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            httpGet.addHeader("authorization", paramMap.get("authorization"));
            httpGet.addHeader("date", paramMap.get("date"));
            httpGet.addHeader("Content-Type", "application/json");
            httpGet.addHeader("x-bce-request-id", "1");
            HttpResponse response = httpclient.execute(httpGet);
            if(response != null){
                HttpEntity resEntity = response.getEntity();
                if(resEntity != null){
                    result = EntityUtils.toString(resEntity,"UTF-8");
                    System.out.println(result);
                }
            }
        }catch (Exception e){
            e.printStackTrace();

        }
    }




}
